package com.begye.smartloan.apptest.disclosure

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtDisclosureBinding
import com.begye.smartloan.apptest.disclosure.adapter.DisclosureIndicatorAdapter
import com.begye.smartloan.apptest.disclosure.adapter.DisclosurePagerAdapter
import com.begye.smartloan.apptest.disclosure.dialog.DisclosureReadDialogFragment
import com.begye.smartloan.apptest.ext.checkNotAgreePermissions
import com.begye.smartloan.apptest.gongong.SysConfigViewModel
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.kefu.KeFuDialogFragment
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.addTouch
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog


@SuppressLint("CustomSplashScreen")
class DisclosureHomeActivity : AppCompatActivity(),
    EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var _binding: AtDisclosureBinding
    private lateinit var _pagerAdapter: DisclosurePagerAdapter
    private lateinit var _disclosureIndicatorAdapter: DisclosureIndicatorAdapter

    private val _sysConfigViewModel by lazy {
        ViewModelProvider(this)[SysConfigViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()

        _binding = AtDisclosureBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
        configUIData()
    }

    private fun configYongHuLiuChengState() {

        _sysConfigViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }
    }

    /**
     * server-->config-->permission-->login
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun configUIState() {

        _sysConfigViewModel.onSysConfigSuccessfulLiveData.observe(this) {
            it?.let { _ ->
                val notAgreeList = checkNotAgreePermissions(SysConfigTool.filterShouYeQuanXiang())
                if (notAgreeList.isEmpty()) {
                    checkLogin()
                } else {
                    // show permission dialog
                    val list = _sysConfigViewModel.configPermissionAdapterItems(notAgreeList)
                    _pagerAdapter.dataList = list
                    _pagerAdapter.notifyDataSetChanged()

                    val indicators = _sysConfigViewModel.configIndicatorAdapterItems(notAgreeList)
                    _disclosureIndicatorAdapter.dataList = indicators
                    _disclosureIndicatorAdapter.notifyDataSetChanged()
                }
            }
        }
    }

    private fun configUIEvent() {
        _pagerAdapter = DisclosurePagerAdapter(this, emptyList()) { type, action, permission ->
            when (action) {

                DisclosurePagerAdapter.SHOW_READ_DIALOG -> {
                    if (permission.isBlank()) {
                        updateItem(type, "YES")
                        findNextItem()
                        checkAllStatus()
                        return@DisclosurePagerAdapter
                    }
                    val dialog = DisclosureReadDialogFragment {
                        EasyPermissions.requestPermissions(
                            this,
                            getString(R.string.disclosure_text_10),
                            type,
                            permission
                        )
                    }
                    dialog.showNow(supportFragmentManager, "readDialog")
                }

                DisclosurePagerAdapter.CLICK_READ_CHECK_BOX -> {
                    _pagerAdapter.notifyDataSetChanged()
                }

                DisclosurePagerAdapter.CLICK_REJECT -> {
                    updateItem(type, "NO")
                    findNextItem()
                    checkAllStatus()
                }

                DisclosurePagerAdapter.CLICK_AGREE -> {
                    if (permission.isBlank()) {
                        updateItem(type, "YES")
                        findNextItem()
                        checkAllStatus()
                        return@DisclosurePagerAdapter
                    }
                    EasyPermissions.requestPermissions(
                        this,
                        getString(R.string.disclosure_text_10),
                        type,
                        permission
                    )
                }
            }
        }
        _binding.atDisclosureViewPager.adapter = _pagerAdapter
        _binding.atDisclosureViewPager.pageMargin = 20
        _binding.atDisclosureViewPager.offscreenPageLimit = 3

        _binding.atDisclosureViewPager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            @SuppressLint("NotifyDataSetChanged")
            override fun onPageSelected(position: Int) {
                for (index in 0 until _disclosureIndicatorAdapter.dataList.size) {
                    val item = _disclosureIndicatorAdapter.dataList[index]
                    item.put("isChecked", index == position)
                }
                _disclosureIndicatorAdapter.notifyDataSetChanged()
            }

            override fun onPageScrollStateChanged(state: Int) {
            }
        })

        _disclosureIndicatorAdapter = DisclosureIndicatorAdapter(emptyList())
        _binding.atDisclosureIndicator.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        _binding.atDisclosureIndicator.adapter = _disclosureIndicatorAdapter

        _binding.atDisclosureNav.initConfig(
            text = "",
            textColor = "#ffffff",
            leftResId = R.drawable.dres_5,
            rightResId = R.drawable.dres_4
        ) {
            if (0 == it) {
                // do not thing
                finish()
            } else if (1 == it) {
                val dialog = KeFuDialogFragment()
                dialog.showNow(supportFragmentManager, "kefu")
            }
        }
    }

    private fun configUIData() {
        _sysConfigViewModel.requestSystemConfiguration()
    }

    private fun checkLogin() {
        finish()
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
//        val notAgreeList = checkNotAgreePermissions(SysConfigTool.filterShouYeQuanXiang())
//        EasyPermissions.requestPermissions(
//            this,
//            getString(R.string.disclosure_text_10),
//            DisclosurePagerAdapter.CATEGORY_ALL,
//            *notAgreeList.toTypedArray<String>()
//        )
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        // update current status
        updateItem(requestCode, "YES")

        // find next item
        findNextItem()

        // check all permission status
        checkAllStatus()
    }

    private fun updateItem(requestCode: Int, result: String) {
        // update current status
        for (index in 0 until _pagerAdapter.dataList.size) {
            val item = _pagerAdapter.dataList[index]
            val type = item.optInt("type", -1)
            if (type == requestCode) {
                item.put("result", result)
                _pagerAdapter.notifyDataSetChanged()
                break
            }
        }
    }

    private fun findNextItem() {
        // find next item
        var nextIndex = -1
        for (index in 0 until _pagerAdapter.dataList.size) {
            val item = _pagerAdapter.dataList[index]
            val type = item.optInt("type", -1)
            if (type != DisclosurePagerAdapter.CATEGORY_APP) {
                val result = item.optString("result", "")
                if (result.isBlank()) {
                    nextIndex = index
                    break
                }
            }
        }

        // scroll to next page smoothly
        if (nextIndex >= 0) {
            _binding.atDisclosureViewPager.setCurrentItem(nextIndex, true)
        }
    }

    private fun checkAllStatus() {
        // check all permission status
        val notAgreeList = checkNotAgreePermissions(SysConfigTool.filterShouYeQuanXiang())
        if (notAgreeList.isEmpty()) {
            checkLogin()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            val notAgreeList = checkNotAgreePermissions(SysConfigTool.filterShouYeQuanXiang())
            EasyPermissions.requestPermissions(
                this,
                getString(R.string.disclosure_text_10),
                DisclosurePagerAdapter.CATEGORY_ALL,
                *notAgreeList.toTypedArray<String>()
            )
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

